import axios from 'axios'
import { Message, Loading } from 'element-ui'

const http = axios.create({
  baseURL:
    process.env.NODE_ENV === 'production'
      ? process.env.VUE_APP_API_URL
      : '/proxy',
  timeout: 1000 * 180,
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json',
  },
})

let loading = null

// ---- 请求拦截 ----
http.interceptors.request.use(
  (config) => {
    const params = config[config.method == 'get' ? 'params' : 'data'] || {}
    params.loading = typeof params.loading == 'boolean' ? params.loading : true
    config.loading = params.loading

    if (params.loading) {
      loading = Loading.service({
        text: 'Loading',
      })
    }

    return config
  },
  (err) => {
    return Promise.reject(err)
  }
)

// ---- 响应拦截 ----
http.interceptors.response.use(
  (res) => {
    if (loading) {
      loading.close()
    }
    return res
  },
  (err) => {
    loading.close()
    Message.error(err.message || 'Network Error')
    return Promise.reject(err)
  }
)

// 封装增删改查方法
const request = {}
const methods = ['get', 'post', 'put', 'delete']

methods.forEach((method) => {
  request[method] = (url = '', params = {}, headers = {}) => {
    return new Promise((resolve, reject) => {
      const options = {
        method: method === 'del' ? 'delete' : method,
        url,
        headers,
      }

      options[method == 'get' ? 'params' : 'data'] = params

      http(options)
        .then((res) => {
          const result = res.data
          const { code, message } = result

          if (code !== 200 && res.config.url !== '/dapp/user') {
            Message.error(message || 'Network Error')
          }

          resolve(result)
        })
        .catch((err) => {
          reject(err)
        })
    })
  }
})

export default request
